<?php

/**
 * Reminders Controller
 *
 * PHP version 5
 *
 * @category Controller
 * @package  Croogo
 * @version  1.0
 * @author   Tran Van Dung <dungtv@ic-t.info>
 * @license  http://www.opensource.org/licenses/mit-license.php The MIT License
 * @link     http://www.croogo.org
 */
class RemindersController extends AppController {

    /**
     * Controller name
     *
     * @var string
     * @access public
     */
    public $name = 'Reminders';

    /**
     * Models used by the Controller
     *
     * @var array
     * @access public
     */
    public $uses = array('Reminder', 'Paymentschedule');

    /**
     * Helpers used by the Controller
     *
     * @var array
     * @access public
     */
    public $helpers = array('Text');
    protected $paginate = array(
        'limit' => 10,
    );

    /**
     * Before executing controller actions
     *
     * @return void
     * @access public
     */
    public function beforeFilter() {
        parent::beforeFilter();

        if ($this->action == 'add' || $this->action == 'edit' || $this->action == 'admin_add' || $this->action == 'admin_edit') {
            $this->Security->validatePost = false;
        }
    }

    /**
     * Admin index
     *
     * @return void
     * @access public
     */
    public function admin_index() {
        $this->set('title_for_layout', __('REMINDER LIST'));

        $scriptSearchBox = $this->scriptSearchBox();
        $this->set('scriptSearchBox', $scriptSearchBox);

        $conditions = array();
        $conditions['Reminder.dtstart >='] = date('Y-m-d');
        $conditions['Reminder.dtstart <='] = date('Y-m-d', strtotime(date('Y-m-d H:i:s')) + 7 * 24 * 60 * 60);
//        $conditions['Reminder.status'] = 0;

        $this->Reminder->recursive = 0;

        $reminders = $this->Reminder->find('all', array(
            'conditions' => $conditions,
            'order' => array('Reminder.dtstart'),
                )
        );
        // check paid
        foreach ($reminders as $key => $reminder) {
            $paymentschedule = $this->Paymentschedule->find('first', array('conditions' => array('id' => $reminder['Reminder']['paymentschedule_id'])));
            $unpaid = (int) $paymentschedule['Paymentschedule']['broker_amount'] - (int) $paymentschedule['Paymentschedule']['paid_amount'];
            if ($unpaid > 0) {
                $reminders[$key]['Reminder']['unpaid'] = $unpaid;
                $reminders[$key]['Reminder']['currency'] = $paymentschedule['Paymentschedule']['currency'];
            } else {
                unset($reminders[$key]);
            }
        }

        $arr = array();
        foreach ($reminders as $reminder) {
            $arr[$reminder['Reminder']['dtstart']][] = $reminder['Reminder'];
        }

        $this->set('arr', $arr);
    }

    public function admin_search() {
        $this->set('title_for_layout', __('REMINDER SEARCH'));

        $scriptSearchBox = $this->scriptSearchBox();
        $this->set('scriptSearchBox', $scriptSearchBox);

        $from = $this->params['named']['from'];
        $this->set('from', $from);
        $to = $this->params['named']['to'];
        $this->set('to', $to);

        $conditions = array();
        $conditions['Reminder.dtstart >='] = $from;
        $conditions['Reminder.dtstart <='] = $to;

        $this->Reminder->recursive = 0;

        $reminders = $this->Reminder->find('all', array(
            'conditions' => $conditions,
            'order' => array('Reminder.dtstart'),
                )
        );
        // check paid
        foreach ($reminders as $key => $reminder) {
            $paymentschedule = $this->Paymentschedule->find('first', array('conditions' => array('id' => $reminder['Reminder']['paymentschedule_id'])));
            $unpaid = (int) $paymentschedule['Paymentschedule']['broker_amount'] - (int) $paymentschedule['Paymentschedule']['paid_amount'];
            if ($unpaid > 0) {
                $reminders[$key]['Reminder']['unpaid'] = $unpaid;
                $reminders[$key]['Reminder']['currency'] = $paymentschedule['Paymentschedule']['currency'];
            } else {
                unset($reminders[$key]);
            }
        }

        $arr = array();
        foreach ($reminders as $reminder) {
            $arr[$reminder['Reminder']['dtstart']][] = $reminder['Reminder'];
        }

        $this->set('arr', $arr);
    }

    public function admin_browse() {
        $this->layout = 'admin_reminder';

        $conditions = array();
        $conditions['Reminder.dtstart >='] = date('Y-m-d');
        $conditions['Reminder.dtstart <='] = date('Y-m-d', strtotime(date('Y-m-d H:i:s')) + 7 * 24 * 60 * 60);
        $conditions['Reminder.status'] = 0;

        $this->Reminder->recursive = 0;

        $reminders = $this->Reminder->find('all', array(
            'conditions' => $conditions,
            'order' => array('Reminder.dtstart'),
                )
        );
        // check paid
        foreach ($reminders as $key => $reminder) {
            $paymentschedule = $this->Paymentschedule->find('first', array('conditions' => array('id' => $reminder['Reminder']['paymentschedule_id'])));
            $unpaid = (int) $paymentschedule['Paymentschedule']['broker_amount'] - (int) $paymentschedule['Paymentschedule']['paid_amount'];
            if ($unpaid > 0) {
                $reminders[$key]['Reminder']['unpaid'] = $unpaid;
                $reminders[$key]['Reminder']['currency'] = $paymentschedule['Paymentschedule']['currency'];
            } else {
                unset($reminders[$key]);
            }
        }

        $arr = array();
        foreach ($reminders as $reminder) {
            $arr[$reminder['Reminder']['dtstart']][] = $reminder['Reminder'];
        }

        $this->set('arr', $arr);
    }

    function admin_alert() {
        $this->Reminder->update_reminder();
        $conditions['Reminder.dtstart >='] = date('Y-m-d');
        $conditions['Reminder.dtstart <='] = date('Y-m-d', strtotime(date('Y-m-d H:i:s')) + 7 * 24 * 60 * 60);
        $conditions['Reminder.status'] = 0;

        $this->Reminder->recursive = 0;

        $reminders = $this->Reminder->find('all', array(
            'conditions' => $conditions,
            'order' => array('Reminder.dtstart'),
                )
        );
        // check paid
        foreach ($reminders as $key => $reminder) {
            $paymentschedule = $this->Paymentschedule->find('first', array('conditions' => array('id' => $reminder['Reminder']['paymentschedule_id'])));
            $unpaid = (int) $paymentschedule['Paymentschedule']['broker_amount'] - (int) $paymentschedule['Paymentschedule']['paid_amount'];
            if ($unpaid > 0) {
                $reminders[$key]['Reminder']['unpaid'] = $unpaid;
                $reminders[$key]['Reminder']['currency'] = $paymentschedule['Paymentschedule']['currency'];
            } else {
                unset($reminders[$key]);
            }
        }
        if (!empty($this->params['requested'])) {
            return count($reminders);
        }
        return false;
    }

    public function admin_view($id = null) {
        $this->layout = 'admin_reminder';
        $this->set('title_for_layout', __('REMINDER DETAIL'));

        $redirect = array('action' => 'index');
        if (!$id) {
            $this->Session->setFlash(__('Invalid Reminder'), 'default', array('class' => 'error'));
            $this->redirect($redirect);
        }
        $conditions = array();
        $conditions['Reminder.id'] = $id;

        $this->Reminder->recursive = 0;

        $reminder = $this->Reminder->find('first', array(
            'conditions' => $conditions,
                )
        );
        // check paid
        $paymentschedule = $this->Paymentschedule->find('first', array('conditions' => array('id' => $reminder['Reminder']['paymentschedule_id'])));
        $unpaid = (int) $paymentschedule['Paymentschedule']['broker_amount'] - (int) $paymentschedule['Paymentschedule']['paid_amount'];
        if ($unpaid > 0) {
            $reminder['Reminder']['unpaid'] = $unpaid;
            $reminder['Reminder']['currency'] = $paymentschedule['Paymentschedule']['currency'];
        } else {
            $this->Session->setFlash(__('Invalid Reminder'), 'default', array('class' => 'error'));
            $this->redirect($redirect);
        }
        $this->set('reminder', $reminder);
    }

    public function admin_ajax_qtip2($id = null) {

        $redirect = array('action' => 'index');
        if (!$id) {
            $this->Session->setFlash(__('Invalid Reminder'), 'default', array('class' => 'error'));
            $this->redirect($redirect);
        }
        $conditions = array();
        $conditions['Reminder.id'] = $id;

        $this->Reminder->recursive = 0;

        $reminder = $this->Reminder->find('first', array(
            'conditions' => $conditions,
                )
        );
        // check paid
        $paymentschedule = $this->Paymentschedule->find('first', array('conditions' => array('id' => $reminder['Reminder']['paymentschedule_id'])));
        $unpaid = (int) $paymentschedule['Paymentschedule']['broker_amount'] - (int) $paymentschedule['Paymentschedule']['paid_amount'];
        if ($unpaid > 0) {
            $reminder['Reminder']['unpaid'] = $unpaid;
            $reminder['Reminder']['currency'] = $paymentschedule['Paymentschedule']['currency'];
        } else {
            $this->Session->setFlash(__('Invalid Reminder'), 'default', array('class' => 'error'));
            $this->redirect($redirect);
        }
        $this->set('reminder', $reminder);
        $this->layout = 'ajax';
    }

    public function admin_accepted($id = null) {
        $this->layout = 'ajax';
        $success = false;
        if ($id != '' && $this->Reminder->read_reminder($id)) {
            $success = true;
        }
        $success = $this->Reminder->encodeData(array('success' => $success), array('json' => true, 'trim' => false));
        $this->set('success', $success);
    }

    public function scriptSearchBox() {
        $output = "
            $(function() {
                $('#search_button').click(function(){
                    var t_from = $('#match_from_id').val().split('/');
                    var from = new Date($('#match_from_id').val());
                    var t_to = $('#match_to_id').val().split('/');
                    var to = new Date($('#match_to_id').val());
                    var count = (to-from)/(1000*60*60*24);
                    if(count>=0) {
                        var q_from = t_from[2]+'-'+t_from[0]+'-'+t_from[1];
                        var q_to = t_to[2]+'-'+t_to[0]+'-'+t_to[1];
                        var temp = 'from:'+q_from+'/to:'+q_to;
                        $(location).attr('href','" . Router::url('/admin/reminders/search/', true) . "' + temp);
                    } else {
                        alert('To date must be greater than or equal to From date');
                    }
                });
            });";
        return $output;
    }

    public function scriptSearchBox2() {
        $output = "
            $(function() {
                $('#dateChange').click(function(){
                    var mo = $('#mo').val();
                    var yr = $('#yr').val();
                    $(location).attr('href','" . Router::url('/admin/reminders/calendar/1', true) . "' + '/' + mo + '/' + yr);
                });
            });";
        return $output;
    }

    function calendars($day, $month, $year, $arr = null, $bool_cur_month = false, $bool_next_month = false) {
        App::import('Helper', 'Html');
        $html = new HtmlHelper(null);

        $prev_month = ($month == 1) ? 12 : $month - 1;
        $prev_year = ($month == 1) ? $year - 1 : $year;
        $next_month = ($month == 12) ? 1 : $month + 1;
        $next_year = ($month == 12) ? $year + 1 : $year;

        $arr_mounth = array(
            1 => 'January',
            2 => 'February',
            3 => 'March',
            4 => 'April',
            5 => 'May',
            6 => 'June',
            7 => 'July',
            8 => 'August',
            9 => 'September',
            10 => 'October',
            11 => 'November',
            12 => 'December'
        );
        $option_mounth = '';
        $selected = '';
        foreach ($arr_mounth as $key => $value) {
            $selected = ($month == $key) ? ' selected="selected"' : '';
            $option_mounth .= '<option' . $selected . ' value="' . $key . '">' . $value . '</option>';
        }

        $option_year = '';
        for ($i = 2000; $i <= 2020; $i++) {
            $selected = ($year == $i) ? ' selected="selected"' : '';
            $option_year .= '<option' . $selected . ' value="' . $i . '">' . $i . '</option>';
        }

        /* draw table */
        $calendar = '<table border="0" cellspacing="1" cellpadding="0" class="mainTableTOC">';
        $calendar .= '
            <tr>
                <td title="Easy PHP Calendar 7" colspan="7" class="monthYearRowTOC">  
                    <table width="100%">
                        <tr>
                            <td class="monthYearTextTOC">' . $arr_mounth[$month] . ' ' . $year . '</td>
                            <td style="text-align: right;">
                                <select id="mo" class="formElements" name="mo">
                                    ' . $option_mounth . '
                                </select>
                                <select id="yr" class="formElements" name="yr">
                                    ' . $option_year . '
                                </select>
                                <input type="submit" value="Go" id="dateChange" class="formButtons" name="dateChange" />
                                <input type="button" name="epcprev" id="epcprev" value="&lt;&lt;" class="formButtons" onclick="$(location).attr(\'href\', \'' . Router::url('/admin/reminders/calendar/1', true) . '/' . $prev_month . '/' . $prev_year .'\');" />
                                <input type="button" name="next" id="next" value="&gt;&gt;" class="formButtons" onclick="$(location).attr(\'href\', \'' . Router::url('/admin/reminders/calendar/1', true) . '/' . $next_month . '/' . $next_year .'\');" />
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>';
//        $calendar .= '<tr>
//                        <th colspan="2"><a href="/bingos/index/1/' . $prev_month . '/' . $prev_year . '" title="Tháng ' . $prev_month . '/' . $prev_year . '">&laquo;</a></th>
//                        <th colspan="3">
//                            Tháng ' . $month . '/' . $year . '
//                        </th>
//                        <th colspan="2"><a href="/bingos/index/1/' . $next_month . '/' . $next_year . '" title="Tháng ' . $next_month . '/' . $next_year . '">&raquo;</a></th>
//                    </tr>';

        /* table headings */
        $headings = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
//        $headings = array('CN', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7');
        $calendar .= '<tr class="dayNamesTextTOC"><td class="dayNamesRowTOC">' . implode('</td><td class="dayNamesRowTOC">', $headings) . '</td></tr>';
//        $calendar .= '<tr><td class="day-name"><div>' . implode('</div></td><td class="day-name"><div>', $headings) . '</div></td></tr>';

        /* days and weeks vars now ... */
        $running_day = date('w', mktime(0, 0, 0, $month, 1, $year));
        $days_in_month = date('t', mktime(0, 0, 0, $month, 1, $year));
        $days_in_this_week = 1;
        $day_counter = 0;
        $dates_array = array();

        /* row for week one */
        $calendar .= '<tr class="rowsTOC">';
//        $calendar .= '<tr>';

        /* print "blank" days until the first of the current week */
        for ($x = 0; $x < $running_day; $x++) {
            $calendar .= '<td class="sOtherTOC">&nbsp;</td>';
//            $calendar .= '<td class="cell-other"><div>&nbsp;</div></td>';
            $days_in_this_week++;
        }

        /* keep going with days.... */
        for ($list_day = 1; $list_day <= $days_in_month; $list_day++) {
            $s = ($running_day == 0 || $running_day == 6) ? 's20TOC0' : 's20TOC';
            $s2 = 'daynumTOC';
            if ($list_day == $day) {
                $s = 's20TOCT';
                $s2 = 'todayTOC';
            }
            $s3 = 's24';
            if ($bool_cur_month == true && $list_day >= $day && $list_day <= ($day + 7)) {
                $s3 = 's23';
            }
            if($bool_cur_month == true && $list_day > ($day + 7)) {
                $s3 = 's21';
            }
            if ($bool_next_month == true) {
                $days_in_prev_month = date('t', mktime(0, 0, 0, $prev_month, 1, $prev_year));
                $alert_in_prev_month = $days_in_prev_month - date('j');
                if($alert_in_prev_month < 7) {
                    if($list_day + $alert_in_prev_month <= 7) {
                        $s3 = 's23';
                    } else {
                        $s3 = 's21';
                    }
                } else {
                    $s3 = 's21';
                }
            }
            if($year > date('Y') || ($year == date('Y') && $month > (date('n') + 1))) {
                $s3 = 's21';
            }
//            $s = ($running_day == 0 || $running_day == 6) ? ' s' : '';
//            if ($list_day == $day) {
//                $s = ' c';
//            }

            /* add in the day number */
            $calendar .= '
                <td class="' . $s . '">
                    <div class="' . $s2 . '">' . $list_day . '</div>';
            if (isset($arr[$list_day])) {
                foreach ($arr[$list_day] as $arr_value) {
                    $calendar .= '
                        <div class="titleTOC">
                            <span class="' . $s3 . '">&nbsp;&nbsp;</span>
                            ' . $html->link($arr_value['summary'], array(
                                'controller' => 'reminders',
                                'action' => 'view',
                                $arr_value['id'],
                                    ), array('rel' => 'reminder', 'class' => 'qtip2')) . '
                        </div>';
                }
            }
            $calendar .= '</td>';
//            $calendar .= '<td class="cell' . $s . '"><div><a href="/bingos/index/' . $list_day . '/' . $month . '/' . $year . '" title="' . $list_day . '/' . $month . '/' . $year . '">' . $list_day . '</a></div></td>';

            if ($running_day == 6):
                $calendar.= '</tr>';
                if (($day_counter + 1) != $days_in_month):
                    $calendar.= '<tr>';
                endif;
                $running_day = -1;
                $days_in_this_week = 0;
            endif;
            $days_in_this_week++;
            $running_day++;
            $day_counter++;
        }

        /* finish the rest of the days in the week */
        if ($days_in_this_week < 8):
            for ($x = 1; $x <= (8 - $days_in_this_week); $x++):
                $calendar .= '<td class="sOtherTOC">&nbsp;</td>';
//                $calendar .= '<td class="cell-other"><div>&nbsp;</div></td>';
            endfor;
        endif;

        /* final row */
        $calendar .= '</tr>';

        /* end the table */
        $calendar .= '</table>';

        /* all done, return result */
        return $calendar;
    }

    function admin_test($day = null, $month = null, $year = null) {
        $this->set('title_for_layout', __('REMINDER CALENDAR'));
        if ($year == null) {
            $day = date('j');
            $month = date('n');
            $year = date('Y');
        }
        $days_in_month = date('t', mktime(0, 0, 0, $month, 1, $year));

        $conditions = array();
        $conditions['Reminder.dtstart >='] = $year . '-' . ($month < 10 ? '0' . $month : $month) . '-01';
        $conditions['Reminder.dtstart <='] = $year . '-' . ($month < 10 ? '0' . $month : $month) . '-' . $days_in_month;
//        $conditions['Reminder.status'] = 0;

        $this->Reminder->recursive = 0;

        $reminders = $this->Reminder->find('all', array(
            'conditions' => $conditions,
            'order' => array('Reminder.dtstart'),
                )
        );
        // check paid
        foreach ($reminders as $key => $reminder) {
            $paymentschedule = $this->Paymentschedule->find('first', array('conditions' => array('id' => $reminder['Reminder']['paymentschedule_id'])));
            $unpaid = (int) $paymentschedule['Paymentschedule']['broker_amount'] - (int) $paymentschedule['Paymentschedule']['paid_amount'];
            if ($unpaid > 0) {
                $reminders[$key]['Reminder']['unpaid'] = $unpaid;
                $reminders[$key]['Reminder']['currency'] = $paymentschedule['Paymentschedule']['currency'];
            } else {
                unset($reminders[$key]);
            }
        }

        $arr = array();
        foreach ($reminders as $reminder) {
            $dayofmounth = date('j', strtotime($reminder['Reminder']['dtstart']));
            $arr[$dayofmounth][] = $reminder['Reminder'];
        }
//        echo '<pre>';print_r($arr);die;

        $scriptSearchBox = $this->scriptSearchBox2();
        $this->set('scriptSearchBox', $scriptSearchBox);

        $calendar = $this->calendars($day, $month, $year, $arr);
        $this->set('calendar', $calendar);
    }

    function admin_calendar($day = null, $month = null, $year = null) {
        $this->set('title_for_layout', __('REMINDER CALENDAR'));
        $bool_cur_month = false;
        $bool_next_month = false;
        if ($year == null) {
            $day = date('j');
            $month = date('n');
            $year = date('Y');
            $bool_cur_month = true;
        } else {
            if($year == date('Y') && $month == date('n')) {
                $day = date('j');
                $bool_cur_month = true;
            }
        }
        
        $next_month = (date('n') == 12) ? 1 : date('n') + 1;
        $next_year = (date('n') == 12) ? date('Y') + 1 : date('Y');
        if($next_month == $month && $next_year == $year) {
            $bool_next_month = true;
        }
            
        $days_in_month = date('t', mktime(0, 0, 0, $month, 1, $year));

        $conditions = array();
        $conditions['Reminder.dtstart >='] = $year . '-' . ($month < 10 ? '0' . $month : $month) . '-01';
        $conditions['Reminder.dtstart <='] = $year . '-' . ($month < 10 ? '0' . $month : $month) . '-' . $days_in_month;
//        $conditions['Reminder.status'] = 0;

        $this->Reminder->recursive = 0;

        $reminders = $this->Reminder->find('all', array(
            'conditions' => $conditions,
            'order' => array('Reminder.dtstart'),
                )
        );
        // check paid
        foreach ($reminders as $key => $reminder) {
            $paymentschedule = $this->Paymentschedule->find('first', array('conditions' => array('id' => $reminder['Reminder']['paymentschedule_id'])));
            $unpaid = (int) $paymentschedule['Paymentschedule']['broker_amount'] - (int) $paymentschedule['Paymentschedule']['paid_amount'];
            if ($unpaid > 0) {
                $reminders[$key]['Reminder']['unpaid'] = $unpaid;
                $reminders[$key]['Reminder']['currency'] = $paymentschedule['Paymentschedule']['currency'];
            } else {
                unset($reminders[$key]);
            }
        }

        $arr = array();
        foreach ($reminders as $reminder) {
            $dayofmounth = date('j', strtotime($reminder['Reminder']['dtstart']));
            $arr[$dayofmounth][] = $reminder['Reminder'];
        }
//        echo '<pre>';print_r($arr);die;

        $scriptSearchBox = $this->scriptSearchBox2();
        $this->set('scriptSearchBox', $scriptSearchBox);
        $scriptSearchBox2 = $this->scriptSearchBox();
        $this->set('scriptSearchBox2', $scriptSearchBox2);

        $calendar = $this->calendars($day, $month, $year, $arr, $bool_cur_month, $bool_next_month);
        $this->set('calendar', $calendar);
    }

}

?>